package com.quectel.core.module.grid.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.grid.dao.GridEventRecordDao;
import com.quectel.core.module.grid.dto.*;
import com.quectel.core.module.grid.entity.GridEventRecordEntity;
import com.quectel.core.module.grid.service.*;
import com.quectel.core.module.grid.vo.GridEventRecordEventCountVo;
import com.quectel.core.module.grid.vo.GridEventRecordStatusCountVo;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/02/03 16:42
 */
@DubboService
public class GridEventRecordServiceImpl implements GridEventRecordService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GridEventRecordServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> GRID_EVENT_RECORD_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "GRID_EVENT_RECORD_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<GridEventRecordDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(GRID_EVENT_RECORD_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private GridService gridService;
    @Autowired
    private GridMemberService gridMemberService;
    @Autowired
    private GridEventRecordDao gridEventRecordDao;
    @Autowired
    private GridEventRecordLogService gridEventRecordLogService;

    @Autowired
    private GridPrimaryEventService gridPrimaryEventService;

    @Autowired
    private GridSecondaryEventService gridSecondaryEventService;

    @Override
    public List<GridEventRecordStatusCountVo> statusCount(Map<String, Object> params) {
        return gridEventRecordDao.statusCount(params);
    }

    @Override
    public List<GridEventRecordEventCountVo> eventCount(Map<String, Object> params) {
        return gridEventRecordDao.eventCount(params);
    }

    /**
     * 通过事件编号查询事件
     *
     * @param eventNo
     * @return
     */
    @Override
    public GridEventRecordDto selectByEventNo(String eventNo) {
        GridEventRecordEntity entity = gridEventRecordDao.selectOne(
                new LambdaQueryWrapper<GridEventRecordEntity>()
                        .eq(GridEventRecordEntity::getEventNo, eventNo)
                        .last(SqlConstants.MYSQL_LIMIT_ONE)
        );
        return paddingField(CopyUtils.copyObj(entity, GridEventRecordDto.class));
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.GRID_EVENT_RECORD_LOG_SEQ_INC_LOCK + "#{#dto.id}"
            }
    )
    @Transactional
    public Long saveOrUpdateWithLog(GridEventRecordDto dto) {
        if (dto.getId() == null) {
            Long id = save(dto);
            dto.setId(id);
        } else {
            updateById(dto);
        }
        if (CollectionUtils.isNotEmpty(dto.getLogList())) {
            List<GridEventRecordLogDto> logList = dto.getLogList();
            logList.forEach(v -> {
                v.setGridEventRecordId(dto.getId());
                gridEventRecordLogService.save(v);
            });
        }
        return dto.getId();
    }


    @Override
    public GridEventRecordDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                GRID_EVENT_RECORD_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public GridEventRecordDto selectById(Long id) {
        GridEventRecordEntity entity = gridEventRecordDao.selectById(id);
        GridEventRecordDto dto = paddingField(CopyUtils.copyObj(entity, GridEventRecordDto.class));

        if (dto != null) {
            List<GridEventRecordLogDto> gridEventRecordLogDtos = gridEventRecordLogService.selectByGridEventRecordId(dto.getId());
            dto.setLogList(gridEventRecordLogDtos);

            if (CollectionUtils.isNotEmpty(gridEventRecordLogDtos)) {
                Optional<GridEventRecordLogDto> first = gridEventRecordLogDtos.stream()
                        .sorted((o1, o2) -> o2.getSeq() - o1.getSeq())
                        .filter(gridEventRecordLogDto -> GridConstant.GridEventRecordLogType.FEEDBACK.getStatus().equals(gridEventRecordLogDto.getHandleStatus())).findFirst();
                if (first.isPresent()) {
                    dto.setSelfHandleResult(first.get().getHandleDetail());
                    dto.setSelfHandlePicturesJson(first.get().getHandlePicturesJson());
                }

            }
        }

        return dto;
    }

    @Override
    public List<GridEventRecordDto> queryList(Map<String, Object> params) {
        List<GridEventRecordEntity> list = gridEventRecordDao.queryList(params);
        List<GridEventRecordDto> result = CopyUtils.copyList(list, GridEventRecordDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属社区等
     *
     * @param dto
     * @return
     */
    private GridEventRecordDto paddingField(GridEventRecordDto dto) {
        if (dto != null) {
            GridPrimaryEventDto gridPrimaryEventDto = gridPrimaryEventService.selectCacheById(dto.getEventPrimaryId());
            if (gridPrimaryEventDto != null) {
                dto.setEventPrimaryName(gridPrimaryEventDto.getName());
            }
            GridSecondaryEventDto gridSecondaryEventDto = gridSecondaryEventService.selectCacheById(dto.getEventSecondaryId());
            if (gridSecondaryEventDto != null) {
                dto.setEventSecondaryName(gridSecondaryEventDto.getName());
            }
            if (dto.getGridId() != null) {
                GridDto gridDto = gridService.selectCacheById(dto.getGridId());
                if (gridDto != null) {
                    dto.setGridName(gridDto.getName());
                }
            }

            if (dto.getGridMemberId() != null) {
                GridMemberDto gridMemberDto = gridMemberService.selectCacheById(dto.getGridMemberId());
                if (gridMemberDto != null) {
                    dto.setGridMemberName(gridMemberDto.getName());
                }
            }

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return gridEventRecordDao.queryTotal(params);
    }

    @Override
    public Long save(GridEventRecordDto dto) {
        GridEventRecordEntity entity = CopyUtils.copyObj(dto, GridEventRecordEntity.class);
        entity.setId(Snowflake.nextId());
        gridEventRecordDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(GridEventRecordDto dto) {
        GridEventRecordEntity entity = CopyUtils.copyObj(dto, GridEventRecordEntity.class);

        gridEventRecordDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(GridEventRecordDto dto) {
        GridEventRecordEntity entity = CopyUtils.copyObj(dto, GridEventRecordEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, gridEventRecordDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        gridEventRecordDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
